package com.blkj.iam.core.schedule;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blkj.iam.common.constant.SsoConstants;
import com.blkj.iam.common.constant.SyncDataConstants;
import com.blkj.iam.common.util.HttpSender;
import com.blkj.iam.system.mapper.*;
import com.blkj.iam.system.model.entity.*;
import com.blkj.iam.system.service.SysSyncDataService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @description: 数据同步服务定时任务
 * @author: Ethan
 * @create: 2025-05-19
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class DataSyncTask {

    private final ClientMapper clientMapper;
    private final SysSyncDataService dataService;
    private final UserMapper userMapper;
    private final DeptMapper deptMapper;
    private final RoleMapper roleMapper;
    private final MenuMapper menuMapper;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void syncData() {
        try {
            List<SysSyncData> dataList = dataService.list(new LambdaQueryWrapper<SysSyncData>().orderByAsc(SysSyncData::getAppId));
            for (SysSyncData data : dataList) {
                String remark = data.getRemark();
                String url = data.getUrl();
                Client client = clientMapper.selectOne(new LambdaQueryWrapper<Client>().eq(Client::getAppId, data.getAppId()));

                HttpSender sender = new HttpSender();
                String result = sender.post(client.getAddress() + url, data.getData());

                JSONObject parseObj = JSONUtil.parseObj(result);
                if (parseObj.getInt(SsoConstants.RSP_CODE) != HttpStatus.HTTP_OK) {
                    log.error("{}数据同步失败：{}", remark, result);
                }

                // 同步ID
                if (remark.equals(SyncDataConstants.USER_ADD)) {
                    JSONObject parsed = JSONUtil.parseObj(data.getData());
                    JSONObject userInfo = parsed.getJSONObject("userInfo");
                    User user = new User();
                    user.setId(userInfo.get("id", Long.class));
                    user.setIdStr(parseObj.getStr(SsoConstants.RSP_DATA));
                    userMapper.updateById(user);
                } else if (remark.equals(SyncDataConstants.ROLE_ADD)) {
                    JSONObject parsed = JSONUtil.parseObj(data.getData());
                    Role role = new Role();
                    role.setId(parsed.get("id", Long.class));
                    role.setIdStr(parseObj.getStr(SsoConstants.RSP_DATA));
                    roleMapper.updateById(role);
                } else if (remark.equals(SyncDataConstants.DEPT_ADD)) {
                    JSONObject parsed = JSONUtil.parseObj(data.getData());
                    Dept dept = new Dept();
                    dept.setId(parsed.get("id", Long.class));
                    dept.setIdStr(parseObj.getStr(SsoConstants.RSP_DATA));
                    deptMapper.updateById(dept);
                } else if (remark.equals(SyncDataConstants.MENU_ADD)) {
                    JSONObject parsed = JSONUtil.parseObj(data.getData());
                    Menu menu = new Menu();
                    menu.setId(parsed.get("id", Long.class));
                    menu.setIdStr(parseObj.getStr(SsoConstants.RSP_DATA));
                    menuMapper.updateById(menu);
                }

                dataService.removeById(data.getId());
                log.error("{}数据同步成功", remark);
            }
        } catch (Exception e) {
            log.error("数据同步服务定时任务执行失败：{}", e.getMessage());
        }
    }

}
